/**
 * Created by lijinde on 2018/3/14.
 */

const express = require('express')
const router = express.Router()
const AV = require('leanengine')
const sha1 = require('js-sha1')
const GenericResponse = require('./generic_response').GenericResponse
/**
 * @swagger
 * /user/register:
 *   post:
 *     description: Register to the application
 *     tags:
 *       - 用户功能
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: username
 *         description: 用户名.
 *         in: formData
 *         required: true
 *         type: string
 *       - name: password
 *         description: 密码.
 *         in: formData
 *         required: true
 *         type: string
 *       - name: email
 *         description: 电子邮件.
 *         in: formData
 *         required: true
 *         type: string
 *       - name: mobile
 *         description: 手机号码.
 *         in: formData
 *         required: false
 *         type: string
 *     responses:
 *       200:
 *         description: 用户注册
 */
router.post('/register',(req, res, next) =>{
  let data = req.body
  if(data && data.username && data.password && data.email){
    let user = new AV.User()
    user.setUsername(data.username)
    user.setPassword(data.password)
    user.setEmail(data.email)
    user.setMobilePhoneNumber(data.mobile)
    user.signUp().then(function (loginedUser) {
        res.status(200).json(GenericResponse('注册成功',loginedUser,true))

    }, (error => {
      res.status(200).json(JSON.stringify(GenericResponse('注册失败',error)))
    }));
  }
  else{
    res.status(200).json(JSON.stringify(GenericResponse('请输入用户名，密码和邮箱')))
  }
})

/**
 * @swagger
 * /user/login:
 *   post:
 *     description: Login to the application
 *     tags:
 *       - 用户功能
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: username
 *         description: 用户名或者电子邮件.
 *         in: formData
 *         required: true
 *         type: string
 *       - name: password
 *         description: 密码.
 *         in: formData
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: 用户登录
 */
router.post('/login',(req, res, next) =>{
  let data = req.body
  if(data && data.username && data.password){
    let user = data.username
    AV.User.logIn(user,data.password).then(result=>{
      req.session.user = result
      res.cookie('user', JSON.stringify({
        username:data.username,
        sign:sha1(result)
      }), { expires: new Date(Date.now() + 1800000), httpOnly: true }).status(200).json(GenericResponse('登陆成功',result,true))
    },error=>{
      res.status(200).json(JSON.stringify(GenericResponse('登录失败',error)))
    })
  }
  else{
    res.status(200).json(JSON.stringify(GenericResponse('请输入用户名/电子邮箱和密码')))
  }
})
module.exports = router
